package com.service.impl;

import com.POJO.User;
import com.mapper.UserMapper;
import com.service.UserService;
import com.util.MybatisConfig;
import lombok.Setter;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Package com.service.impl
 * @Date 2024-05-23
 * @Description 用户服务接口的实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Setter
    private UserMapper userMapper;

    private SqlSession sqlSession;

    // 使用MyBatis配置获取SqlSession和UserMapper
    private void openSession(){
        sqlSession = MybatisConfig.getSession();
        userMapper = sqlSession.getMapper(UserMapper.class);
    }

    /**
     * 根据用户名获取用户信息
     * @param username 用户名
     * @return 用户对象
     */
    @Override
    public User getUser(String username) {
        openSession();
        try {
            return userMapper.getUser(username);
        }catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            sqlSession.close();
        }
    }

    /**
     * 获取所有用户信息
     * @return 包含用户对象的列表
     */
    @Override
    public List<User> getAllUser() {
        openSession();
        try {
            return userMapper.getAllUser();
        }catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            sqlSession.close();
        }
    }

//    /**
//     * 根据用户ID删除用户
//     * @param userId 用户ID
//     * @return 删除操作的结果
//     */
//    @Override
//    public int deleteUser(int userId) {
//        return userMapper.deleteUser(userId);
//    }

    /**
     * 更新用户信息
     * @param user 用户对象
     * @return 更新操作的结果
     */
    @Override
    public int updateUser(User user) {
        openSession();
        userMapper.updateUser(user);
        sqlSession.commit();
        sqlSession.close();
        return 0;
    }
}
